package com.tsinkai.ettp.practice;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA3Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.jcajce.provider.digest.SHA3;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SHAPra {
	private static String src = "hello world!";
	
	public static void main(String[] args) {
		jdkSHA1();
		bcSHA();
		ccSha();
	}
	
	/**
	 * jdk实现方式
	 */
	public static void jdkSHA1() { 
		try {
			//getInstance("SHA-1")该参数可填列表：MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512
			//填写SHA等同于SHA-1
			MessageDigest md = MessageDigest.getInstance("SHA");//默认调用jdk实现：sun.security.provider.SHA
//			MessageDigest md = MessageDigest.getInstance("SHA224");//默认调用bc实现：org.bouncycastle.jcajce.provider.digest.SHA224
//			MessageDigest md = MessageDigest.getInstance("SHA256");//默认调用bc实现：org.bouncycastle.jcajce.provider.digest.SHA256
//			MessageDigest md = MessageDigest.getInstance("SHA384");//默认调用bc实现：org.bouncycastle.jcajce.provider.digest.SHA384
//			MessageDigest md = MessageDigest.getInstance("SHA512");//默认调用bc实现：org.bouncycastle.jcajce.provider.digest.SHA512
//			md.update(src.getBytes());//使用update后后续方法不需要再添加字节数组
			System.out.println("jdk SHA-1:" + Hex.encodeHexString(md.digest(src.getBytes())));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Bouncy Castle 实现方式
	 */
	public static void bcSHA() {
		Digest digest = new SHA1Digest();
//		Digest digest = new SHA224Digest();
//		Digest digest = new SHA256Digest();
//		Digest digest = new SHA384Digest();
//		Digest digest = new SHA512Digest();
		digest.update(src.getBytes(),0,src.getBytes().length);
		byte[] sha1Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(sha1Bytes, 0);
		System.out.println("bc sha-1:" + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));
	}
	
	/**
	 * Commons condc实现方式
	 */
	public static void ccSha() {
		System.out.println("cc sha1:" + DigestUtils.sha1Hex(src));//改方法底层仍是调用MessageDigest.getInstance("SHA-1");
		System.out.println("CC SHA256:"+DigestUtils.sha256Hex(src));
		System.out.println("CC SHA384:"+DigestUtils.sha384Hex(src));
		System.out.println("CC SHA512:"+DigestUtils.sha512Hex(src));
		
	}
}
